package com.yexx.nacos.controller;

import com.yexx.lock.DistributedLocker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Description: redisson 测试
 *
 * @author: zuomin (myleszelic@outlook.com)
 * @date: 2020/11/12-17:17
 */
@RestController
@RequestMapping("/api/public/limit")
public class LimitTestController {


    private ExecutorService executorService1 = Executors.newFixedThreadPool(10);
    private ExecutorService executorService2 = Executors.newFixedThreadPool(10);

    @Autowired
    DistributedLocker distributedLocker;


    @GetMapping("/do_lock_incr")
    public int testLockInrc() throws InterruptedException {

        CountDownLatch countDownLatch = new CountDownLatch(100);

        final int[] incr = {0};

        for (int i = 0; i < 100; i++) {
            executorService1.execute(() -> {
                try {
                    if (distributedLocker.lock("abcd")) {
                        incr[0]++;
                    }
                } finally {
                    distributedLocker.unlock("abcd");
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        return incr[0];
    }

    @GetMapping("/do_incr")
    public int testInrc() throws InterruptedException {

        CountDownLatch countDownLatch = new CountDownLatch(100);

        final int[] incr = {0};

        for (int i = 0; i < 100; i++) {
            executorService2.execute(() -> {
                incr[0]++;
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        return incr[0];
    }
}
